<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>

    <!-- 导入依赖-->
    <link rel="stylesheet" href="../css/index.css">
    <link rel="stylesheet" href="../css/all.css">
    <link rel="stylesheet" href="../css/google-fonts.css">
    <script type="text/javascript" src="../js/md5.js"></script>
    <link rel="stylesheet" href="../node_modules/mdbootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../node_modules/mdbootstrap/css/mdb.min.css">
    <link rel="stylesheet" href="../node_modules/mdbootstrap/css/style.css">

</head>

<body style="background-color: #42464c">
<!-- 导入依赖-->
<script type="text/javascript" src="../node_modules/mdbootstrap/js/jquery.min.js"></script>
<script type="text/javascript" src="../node_modules/mdbootstrap/js/popper.min.js"></script>
<script type="text/javascript" src="../node_modules/mdbootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../node_modules/mdbootstrap/js/mdb.min.js"></script>

<!-- 页面上方信息栏 -->
<div>
    <div class="bg-info clearfix" style="background-color: #26282c !important;">
        <!-- 标题-->
        <img style="margin-left: 20px" src="../img/logo.png">
        <h4 class="bar" style="color: #ffffff">聊天吧</h4>
        <div class="avatar-name" onclick="">
            <!-- 头像-->
            <img class="avatar"
                 src="https://tse4-mm.cn.bing.net/th/id/OIP-C.icmtPAEBY4b34eRiPY8SQgAAAA?w=187&h=186&c=7&r=0&o=5&dpr=1.25&pid=1.7"
                 id="personal-avatar" onclick="gotoPersonalPage()">
            <!-- 名字-->
            <h5 class="name"><a class="name" id="personal-name" href="javascript:gotoPersonalPage()"
                                style="color: #ffffff"></a></h5>
        </div>

        <!-- 创建房间按钮-->
        <button id="createRoomBtn" class="btn btn-primary createRoom" onclick="createRoom()">创建房间</button>

        <!-- 退出按钮-->
        <button id="quiteBtn" class="btn btn-secondary createRoom" onclick="quite()">退出登录</button>

        <!-- 退出按钮-->
        <button id="returnBigRoom" class="btn btn-secondary createRoom" onclick="returnBigRoom()">返回大房间</button>
    </div>
</div>

<!-- 搜索功能 -->
<div style="margin-left: 40%;margin-top: 20px;">
    <div class="form-outline mb-4" style="display: inline-block;">
        <input type="text" id="searchtext" style="height: 45px" placeholder="请输入房间号ID"
               class="form-control"/>
    </div>
    <div style="display: inline-block; border-radius: 8px;">
        <button class="btn btn-primary" onclick="searchRoom()">搜索</button>
    </div>
</div>

<!-- 搜索房间列表  -->
<div id="searchroomCards" style="margin: 3% 3% 3% 3%; text-align: center;">
    <div id="noResults" style=""><font color="#fffaf0">没有找到此房间</font></div>
</div>

<!-- 房间列表 -->
<div id="roomListCards" style="margin: 3% 3% 3% 3%; text-align: center;">
    <!--房间卡片示例-->
    <!--    <div class="card"-->
    <!--         style="width: 18rem;display: inline-flex;margin: 3% 3% 3% 3%;align-items: center;justify-content: flex-start;"-->
    <!--         onclick="enterRooms(17)">-->
    <!--        &lt;!&ndash;    <img class="card-img-top" src="https://mdbootstrap.com/img/Photos/Others/images/43.webp" alt="Card image cap">&ndash;&gt;-->
    <!--        <div class="card-body">-->
    <!--            &lt;!&ndash; 房间名 &ndash;&gt;-->
    <!--            <h3 class="card-title">房间名:安全屋</h3>-->
    <!--            &lt;!&ndash; 房间ID &ndash;&gt;-->
    <!--            <h5>ID:1107</h5>-->
    <!--            &lt;!&ndash; 创建者 &ndash;&gt;-->
    <!--            <h5>创建者:穿山甲</h5>-->
    <!--            &lt;!&ndash; 人数 &ndash;&gt;-->
    <!--            <h5>人数:3/10</h5>-->
    <!--            <p class="card-text">房间介绍:一堆游戏爱好者的聚集地</p>-->
    <!--            &lt;!&ndash; <a href="https://mdbootstrap.com/education/bootstrap/quick-start/" class="stretched-link">Go somewhere</a>&ndash;&gt;-->
    <!--        </div>-->
    <!--    </div>-->

</div>

<!--创建房间弹出提示-->
<div id="createRoomPrompt">
    <div class="card prompt">
        <div class="card-body">
            <h3 class="card-title" style="color:black">请填写以下信息:</h3>
            <div>
                <!-- 房间名称 -->
                <div class="form-outline mb-4">
                    <label class="form-label" for="form1Example1">房间名:</label>
                    <input type="email" id="form1Example1" placeholder="请输入房间名称" class="form-control"/>
                </div>

                <!-- 私密房间 -->
                <div>
                    <!-- 房间密码 -->
                    <div class="form-outline mb-4" style="display: inline-block; width: 50%;">
                        <label class="form-label" for="roomPassword">房间密码:</label>
                        <input type="password" id="roomPassword" disabled class="form-control"/>
                    </div>
                    <!-- 设为私密房间 -->
                    <div class="row mb-4" style="display: inline-block;width: 50%;">
                        <div class="col d-flex justify-content-center">
                            <!-- Checkbox -->
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="checkbox"
                                       placeholder="请输入4-16字符为房间密码"
                                       onclick="checkboxOnclick(this)"/>
                                <label class="form-check-label" for="checkbox">设为私密房间</label>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 房间名称 -->
                <div class="form-outline mb-4">
                    <label class="form-label" for="form1Example3">房间人数:</label>
                    <input type="number" min="1" max="10" id="form1Example3" placeholder="请输入1-10的数字"
                           class="form-control"/>
                </div>

                <!-- 房间类型 -->
                <div>
                    <label class="form-label" for="flexRadioDefault1">房间类型:</label>
                    <br>
                    <!-- 音频房间-->
                    <div class="form-check" style="display: inline-block;">
                        <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1"
                               checked/>
                        <label class="form-check-label" for="flexRadioDefault1">语音</label>
                    </div>

                    <!-- 视频房间 -->
                    <div class="form-check" style="display: inline-block; margin-left: 20px;">
                        <input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault2"/>
                        <label class="form-check-label" for="flexRadioDefault2">视频</label>
                    </div>
                </div>

                <!-- 按钮 -->
                <div>
                    <button class="btn btn-primary createRoom" onclick="confirmCreateRoom()">创建</button>
                    <button class="btn btn-secondary createRoom" onclick="cancleCreateRoom()">取消</button>
                </div>
            </div>

        </div>
    </div>

</div>

<script>

    getPersonalInfo();

    // 全局变量uid
    let uid;

    // 默认隐藏创建房间弹窗
    document.getElementById("createRoomPrompt").style.display = "none";
    document.getElementById("searchroomCards").style.display = "none";

    // 退出登录
    function quite() {
        $.ajax({
            url: "/logout",
            type: "get",
            success: function () {
                window.location.href = "/login.html"
            }
        })
    }

    // 创建房间
    function createRoom() {
        // 隐藏页面内容
        document.getElementById("createRoomBtn").style.display = "none";
        document.getElementById("quiteBtn").style.display = "none";
        document.getElementById("roomListCards").style.display = "none";
        document.getElementById("createRoomPrompt").style.display = "";
    }

    // 单选框判断
    let checkBox = document.getElementById("checkbox");

    function checkboxOnclick(checkBox) {
        if (checkBox.checked === true) {
            document.getElementById("roomPassword").disabled = "";
        } else {
            document.getElementById("roomPassword").value = "";
            document.getElementById("roomPassword").disabled = "disabled";
        }
    }

    // 确认创建房间
    function confirmCreateRoom() {
        var checkbox = document.getElementById("checkbox");
        var roomname = $("#form1Example1").val();
        var limits = $("#form1Example3").val();
        // 房间类型 0是语音，1是视频
        var type = 0;
        // 0代表房间非私密
        var secret = 0;
        var pwd = "";
        if (checkbox.checked) {
            secret = 1;
            pwd = $("#roomPassword").val();
            console.log(pwd.length);
        }
        if (document.getElementById("flexRadioDefault2").checked) {
            type = 1;
        }
        console.log(roomname + "  " + limits);

        if (roomname == "" || limits == "" || limits > 10 || limits <= 0) {
            alert("不能输入空值或者房间人数无效");

        } else {
            console.log(pwd.length);
            if (secret == 1 && pwd.length == 0) {
                alert("密码不能为空")
            } else {
                var time = Date.parse(new Date());
                pwd = hex_md5(pwd);
                $.ajax({
                    url: "/index/createroom",
                    type: "post",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    async: false,
                    data: JSON.stringify(
                        {
                            "roomname": roomname,
                            "upperlimits": limits,
                            "secret": secret,
                            "password": pwd,
                            "createtime": time,
                            "type": type
                        }
                    ),
                    success: function (data) {
                        if (data.er == "0") {
                            alert("创建成功");
                            window.location.href = "/views/index.html"
                        }
                    }
                })
            }
        }
    }

    // 取消创建房间
    function cancleCreateRoom() {
        // 显示页面内容
        document.getElementById("createRoomBtn").style.display = "";
        document.getElementById("quiteBtn").style.display = "";
        document.getElementById("roomListCards").style.display = "";
        document.getElementById("createRoomPrompt").style.display = "none";
    }

    // 创建房间列表卡片
    function createRoomsCard() {
        $.ajax({
            url: "/index/getRoomsList",
            type: "get",
            success: function (data) {
                for (let i = 0; i < data.length; i++) {
                    // console.log(data[i]);
                    createSingleCard(data[i]);
                }
            }
        })
    }

    // 房间卡片填充
    function createSingleCard(room) {
        //判断房间类型
        let roomType;
        if (room.type === 0) {
            roomType = "语音房间";
        } else {
            roomType = "视频房间";
        }
        $("#roomListCards").append('<div class="card roomcard"\n' +
            '         style="width: 18rem;display: inline-flex;margin: 3% 3% 3% 3%;align-items: center;justify-content: flex-start;background-color: #6a6d74 ; cursor: pointer;"' +
            '         onclick="enterRooms(' + room.roomid + ')">\n' +
            '        <!--    <img class="card-img-top" src="https://mdbootstrap.com/img/Photos/Others/images/43.webp" alt="Card image cap">-->\n' +
            '        <div class="card-body">\n' +
            '            <!-- 房间名 -->\n' +
            '            <h3 class="card-title">房间名:' + room.roomname + '</h3>\n' +
            '            <!-- 房间ID -->\n' +
            '            <h5>ID:' + room.roomid + '</h5>\n' +
            '            <!-- 创建者 -->\n' +
            '            <h5>创建者:' + room.creator + '</h5>\n' +
            '            <!-- 人数 -->\n' +
            '            <h5>' + roomType + '</h5>\n' +
            '            <!--<p class="card-text">房间介绍:一堆游戏爱好者的聚集地</p>\n-->' +
            '            <!-- <a href="https://mdbootstrap.com/education/bootstrap/quick-start/" class="stretched-link">Go somewhere</a>-->\n' +
            '        </div>\n' +
            '    </div>');
    }

    // 发送进入房间请求
    function enterRooms(roomId) {
        alert("进入房间" + roomId);
        $.ajax({
            url: "/index/enterRoom?roomId=" + roomId,
            type: "get",
            success: function (data) {
                var json = JSON.parse(data);
                console.log(json, typeof json);
                // 这里进行判断，secret为0，无需密码，连接进入房间
                // 值为1，弹出密码填写框
                var secret = json.secret;
                var type = json.type;
                console.log("密码状态" + json.secret);
                if (secret === 0 && type === 0) {// 没有密码，语音房间
                    window.location.href = "/views/inRoom.html?roomId=" + json.roomId + "&uid=" + json.uid + "&roomName=" + json.roomname;
                } else if (secret === 1 && type === 0) {// 有密码，语音房间
                    // 这里需要密码判断框


                    var pwd = window.prompt("请输入密码：", "在这里输入");
                    if (pwd != null) {
                        pwd = hex_md5(pwd);
                        console.log(pwd);
                        judgeRoomPwd(json.roomId, pwd, json.uid, json.roomname);
                    }

                } else if (secret === 1 && type === 1) {// 有密码，视频房间

                    var pwd = window.prompt("请输入密码：", "在这里输入");
                    if (pwd != null) {
                        pwd = hex_md5(pwd);
                        judgeRoomPwd(json.roomId, pwd, json.uid, json.roomname);
                    }
                } else if (secret === 0 && type === 1) {// 无密码，视频房间
                    window.location.href = "/views/inVideoRoom.html?roomId=" + json.roomId + "&uid=" + json.uid + "&roomName=" + json.roomname;
                }
            }
        })
    }

    //   判断房间密码是否正确
    function judgeRoomPwd(nowroomid, pwd, nowroomuid, nowroomname) {
        $.ajax({
            url: "/index/judgeRoomPwd",
            type: "post",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: false,
            data: JSON.stringify({
                "roomId": nowroomid,
                "pwd": pwd,
            }),
            success: function (data) {
                if (data.er == "0") {
                    alert("进入失败!")
                } else if (data.er == "1") {
                    pwd = window.prompt("密码错误，请重新输入", "在这里输入");
                    if(pwd!=null){
                        judgeRoomPwd(nowroomid, pwd);
                    }
                } else {
                    window.location.href = "/views/inRoom.html?roomId=" + nowroomid + "&uid=" + nowroomuid + "&roomName=" + nowroomname;
                }
            }
        })
    }

    // 得到头像和名字
    function getPersonalInfo() {
        $.ajax({
            url: "/index/personalInfo",
            type: "get",
            success: function (data) {
                let json = JSON.parse(data);
                let personalname = json.name;
                let personalavatar = json.photo;
                uid = json.uid;
                console.log(uid)
                console.log(personalname);
                console.log(personalavatar);
                document.getElementById("personal-name").innerText = personalname;
                document.getElementById("personal-avatar").src = personalavatar;

            }
        })
    }

    // 搜索相关功能
    document.getElementById("returnBigRoom").style.display = "none";

    // 搜索功能
    function searchRoom() {
        document.getElementById("returnBigRoom").style.display = "";
        document.getElementById("roomListCards").style.display = "none";
        document.getElementById("searchroomCards").style.display = "";
        var roomid = document.getElementById("searchtext").value;
        $.ajax({
            url: "/index/getRoomsList",
            type: "get",
            success: function (data) {
                var tmp = 0;
                for (let i = 0; i < data.length; i++) {
                    if (roomid == data[i].roomid) {
                        document.getElementById("noResults").style.display = "none";
                        createSearchCard(data[i]);
                        tmp = 1;
                        break;
                    }
                }
                if (tmp == 0) {
                    document.getElementById("noResults").style.display = "";
                }
            }
        })
    }

    // 返回大房间
    function returnBigRoom() {
        document.getElementById("roomListCards").style.display = "";
        document.getElementById("searchroomCards").style.display = "none";
        document.getElementById("returnBigRoom").style.display = "none";
        document.getElementById("searchtext").value = "";
    }

    // 创建搜索房间的结果列表
    function createSearchCard(room) {
        //判断房间类型
        let roomType;
        if (room.type === 0) {
            roomType = "语音房间";
        } else {
            roomType = "视频房间";
        }
        $("#searchroomCards").append('<div class="card roomcard"\n' +
            '         style="width: 18rem;display: inline-flex;margin: 3% 3% 3% 3%;align-items: center;justify-content: flex-start;background-color: #6a6d74 ;cursor: pointer;" ' +
            '         onclick="enterRooms(' + room.roomid + ')">\n' +
            '        <!--    <img class="card-img-top" src="https://mdbootstrap.com/img/Photos/Others/images/43.webp" alt="Card image cap">-->\n' +
            '        <div class="card-body">\n' +
            '            <!-- 房间名 -->\n' +
            '            <h3 class="card-title">房间名:' + room.roomname + '</h3>\n' +
            '            <!-- 房间ID -->\n' +
            '            <h5>ID:' + room.roomid + '</h5>\n' +
            '            <!-- 创建者 -->\n' +
            '            <h5>创建者:' + room.creator + '</h5>\n' +
            '            <!-- 人数 -->\n' +
            '            <h5>' + roomType + '</h5>\n' +
            '            <!--<p class="card-text">房间介绍:一堆游戏爱好者的聚集地</p>\n-->' +
            '            <!-- <a href="https://mdbootstrap.com/education/bootstrap/quick-start/" class="stretched-link">Go somewhere</a>-->\n' +
            '        </div>\n' +
            '    </div>');
    }

    // 进入个人主页
    function gotoPersonalPage() {
        window.location.href = "/views/personalPage.html?uid=" + uid
    }

    // 页面加载完毕后执行的函数
    $(function () {
        $("#quiteBtn").click(function () {
            quite();
        })
        createRoomsCard();
    })

    // 获取url里的参数
    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] === variable) {
                return pair[1];
            }
        }
        return (false);
    }

    if (getQueryVariable("roomId") !== false) {
        enterRooms(getQueryVariable("roomId"));
    }

</script>

</body>
</html>


